package com.junzhiit.nengji.app.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.bainaeco.framework.util.DateUtil;
import com.junzhiit.nengji.app.rabbitmq.RabbitMQService;
import com.junzhiit.nengji.app.service.ShopService;
import com.junzhiit.nengji.app.web.exception.LimitControlException;
import com.junzhiit.nengji.app.web.exception.SendSMSFaileException;
import com.junzhiit.nengji.app.web.exception.ShopNotFoundException;
import com.junzhiit.nengji.app.web.exception.WechatConfigNotFoundException;
import com.junzhiit.nengji.app.web.util.Constants;
import com.junzhiit.nengji.app.web.util.aliyun.AliyunOSSClientUtil;
import com.junzhiit.nengji.app.web.util.aliyun.SmsUtil;
import com.junzhiit.nengji.app.web.util.aliyun.bean.SMSParams;
import com.junzhiit.nengji.app.web.util.wechat.WeChatUtils;
import com.junzhiit.nengji.app.web.vo.ResultVO;
import com.junzhiit.nengji.app.web.vo.ShopEditVO;
import com.junzhiit.nengji.app.web.vo.ShopUpdateVO;
import com.junzhiit.nengji.app.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.bo.ShopBO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.WechatConfigDAO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.WechatConfig;
import com.junzhiit.nengji.model.enums.AuditStatus;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.ShopIsRecentChange;

@Service
public class ShopServiceImpl extends BaseServiceImpl implements ShopService {

	@Autowired
	private ShopDAO shopDAO;


	@Autowired
	private SystemUserCacheDAO systemUserCacheDAO;

	@Autowired
	private WechatConfigDAO wechatConfigDAO;
	
	@Autowired
	private RabbitMQService rabbitMQService;

	@Value("${upload.temp}")
	private String uploadPath;

	@Value("${upload.mall.shop}")
	private String shopPath;

	@Value("${upload.mall.shop.qrcode}")
	private String shopQrcodePath;
	
	//阿里云API的bucket名称
	@Value("${oss.backet.name}")
	private String backetName;

	@Override
	public ResultVO findById(String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		if (shop.getWithdrawalMoney() == null) {
			shop.setWithdrawalMoney(0.00);
		}

		result.setData(shop);

		return result;
	}

	@Override
	public ResultVO getShopById(String id) {
		ResultVO result = new ResultVO();
		Shop shop = shopDAO.query(id);
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		shop.setIsRecentChange(ShopIsRecentChange.NO.toIntStatus());
		shopDAO.update(shop);
		ShopBO shopBO = shopDAO.getShopById(id);
		if (shopBO.getExpireTime() != null) {
			shopBO.setShopExpireTime(DateUtil.format(shopBO.getExpireTime()));
		}
		result.setData(shopBO);
		return result;
	}

	@Override
	@Transactional
	public ResultVO update(ShopUpdateVO shopUpdateVO) {
		ResultVO result = new ResultVO();
		
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(shopUpdateVO.getSessionId()),
				SystemUserSessionVO.class);
		Shop shops = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shops == null) {
			throw new ShopNotFoundException("门店找不到");
		}
		BeanUtils.copyProperties(shopUpdateVO, shops);
		if (shopUpdateVO.getExpireTime() != null) {
			shops.setExpireTime(DateUtil.getDateEnd(shopUpdateVO.getExpireTime()));
			shops.setIsRemind(Is.NO.toIntValue());
			shops.setIsRemindExpire(Is.NO.toIntValue());
		}
		shops.setIsSetType(Is.YES.toIntValue());
		shopDAO.update(shops);
		rabbitMQService.shopUpdate(shops);
		return result;
	}

	@Override
	public ResultVO editShop(ShopEditVO shopEditVO) {
		ResultVO result = new ResultVO();

		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(shopEditVO.getSessionId()), SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		
		Shop updateShop = new Shop();
		BeanUtils.copyProperties(shopEditVO, updateShop);
		if (shop.getAuditStatus() == AuditStatus.AUDITFAIL.toIntStatus()) {
			updateShop.setAuditStatus(AuditStatus.AUDIT.toIntStatus());
		} else {
			updateShop.setIsRecentChange(ShopIsRecentChange.YES.toIntStatus());
		}
		List<String> bannerImages = shopEditVO.getBannerImages();
		if (StringUtils.isNoneBlank(shop.getBannerImages())) {
			List<String> oldBannderImages = Arrays.asList(StringUtils.split(shop.getBannerImages(), ","));
			bannerImages.addAll(oldBannderImages);
		}
		updateShop.setBannerImages(StringUtils.join(bannerImages, ","));
		updateShop.setId(shop.getId());
		boolean data = shopDAO.update(updateShop);

		if (StringUtils.isNotBlank(shopEditVO.getShopHeadImgUrl())) {
			//FileUtil.moveFile(uploadPath + shopEditVO.getShopHeadImgUrl(), shopPath);
			boolean is = AliyunOSSClientUtil.moveFile(backetName,shopEditVO.getShopHeadImgUrl(), shopPath, uploadPath);
			if(is){
				AliyunOSSClientUtil.removeFile(backetName, uploadPath+shopEditVO.getShopHeadImgUrl());
			}
		}
		if (StringUtils.isNotBlank(shopEditVO.getBackgroundImage())) {
			//FileUtil.moveFile(uploadPath + shopEditVO.getBackgroundImage(), shopPath);
			boolean is = AliyunOSSClientUtil.moveFile(backetName,shopEditVO.getBackgroundImage(), shopPath, uploadPath);
			if(is){
				AliyunOSSClientUtil.removeFile(backetName, uploadPath+shopEditVO.getBackgroundImage());
			}
		}
		if(bannerImages!=null && bannerImages.size()>0){
			for (String bannerImage : bannerImages) {
				//FileUtil.moveFile(uploadPath + bannerImage, shopPath);
				boolean is = AliyunOSSClientUtil.moveFile(backetName,bannerImage, shopPath, uploadPath);
				if(is){
					AliyunOSSClientUtil.removeFile(backetName, uploadPath+bannerImage);
				}
			}
		}
		
		rabbitMQService.shopUpdate(updateShop);
		result.setData(data);
		return result;
	}

	@Override
	public ResultVO delShopHeadImgUrl(String shopHeadImgUrl, String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		shop.setShopHeadImgUrl(null);
		shopDAO.update(shop, true);

		//FileUtil.removeFile(shopPath + shopHeadImgUrl);
		AliyunOSSClientUtil.removeFile(backetName, shopPath+shopHeadImgUrl);
		return result;
	}

	@Override
	public ResultVO delBackgroundImage(String backgroundImage, String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}
		shop.setBackgroundImage(null);
		shopDAO.update(shop, true);

		AliyunOSSClientUtil.removeFile(backetName, shopPath + backgroundImage);
		return result;
	}

	@Override
	public ResultVO delBannerImages(String bannerImage, String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		Shop shop = shopDAO.query(systemUserSessionVO.getSystemId());
		if (shop == null) {
			throw new ShopNotFoundException("店铺不存在");
		}

		String[] arr = StringUtils.split(shop.getBannerImages(), ",");
		List<String> oldBannderImages = new ArrayList<String>(Arrays.asList(arr));
		int index = oldBannderImages.indexOf(bannerImage);
		if (index != -1) {
			oldBannderImages.remove(index);
			shop.setBannerImages(StringUtils.join(oldBannderImages, ","));
		}

		shopDAO.update(shop, true);

		AliyunOSSClientUtil.removeFile(backetName, shopPath + bannerImage);
		return result;
	}

	@Override
	public ResultVO createQrcode(String shopId) {
		ResultVO result = new ResultVO();
		Shop shop = shopDAO.query(shopId);
		String wechatCodeUrl=shopId + ".png";
		if(shop.getIsPlatform() == Is.YES.toIntValue()){
			WechatConfig wechatConfig = wechatConfigDAO.getWechatConfigByCsId(shopId);
			if(wechatConfig == null){
				throw new WechatConfigNotFoundException("微信配置未配置");
			}
			
			WeChatUtils.wxQRCode(wechatConfig,backetName,shop.getCode(), shop.getId(), shopQrcodePath, wechatCodeUrl,Constants.SHOP_URL);
			shop.setWechatCodeUrl(wechatCodeUrl);
			shopDAO.update(shop);
			
		}else{
			WeChatUtils.wxQRCode(backetName,shop.getCode(), shop.getId(), shopQrcodePath, wechatCodeUrl,Constants.SHOP_URL);
			shop.setWechatCodeUrl(wechatCodeUrl);
			shopDAO.update(shop);
		}
		result.setData(wechatCodeUrl);
		return result;
	}

	public void sendRemindInfo() {
		Date now = new Date();
		String date = null;
		List<Shop> shops = shopDAO.getSoonExpireShop();
		for (Shop shop : shops) {
			if(shop.getMobilePhone()==null||shop.getMobilePhone()==""){
				throw new SendSMSFaileException("该店铺无手机号码,无法发送手机验证码");
			}
			if (shop.getExpireTime() != null && DateUtil.getDate(shop.getExpireTime(), -15).getTime() < now.getTime()) {
				date = DateUtil.format(shop.getExpireTime());
				SMSParams sms = new SMSParams();
				sms.setSignName(SmsUtil.ALIYUN_SMS_SIGN_NAME);
				sms.setTemplateCode(SmsUtil.ALIYUN_SMS_CONTRACT_EXPIRE);
				sms.setPhoneNumbers(new String[] { shop.getMobilePhone() });
				sms.setParamKeys(new String[] { SmsUtil.KEY_DATE, SmsUtil.KEY_SEND_MOBLIE_PHONE });
				sms.setParamValues(new String[] { date, SmsUtil.REMIND_CLOSE_SERVICE });
				try {
					SendSmsResponse response = SmsUtil.sendSms(sms);
					if (response.getCode() != null && response.getCode().equals("OK")) {
						shop.setIsRemind(Is.YES.toIntValue());
						shopDAO.update(shop);
					} else if (response.getCode() != null && response.getCode().equals(SmsUtil.LIMIT_CONTROL_ERROR)) {
						throw new LimitControlException("不能过于频繁发送验证码,请稍后再发");
					} else {
						throw new SendSMSFaileException("无法发送手机验证码");
					}
				} catch (ClientException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
